package tk0084.dev.google.quiz.lite;

import java.util.Arrays;

/**
 * tableクラスの処理をすべてstaticにしたクラス
 * @author ohashi
 *
 */
public class StaticTable {

	public static char BLOCK = '=';
	public static char EMPTY = '0';

	public static boolean canUp(char[] chars, int row, int col, int emptyIndex) {
		int index = emptyIndex - col;
		if (index < 0) {
			return false;
		}
		if (chars[index] == BLOCK) {
			return false;
		}
		return true;
	}

	public static boolean canDown(char[] chars, int row, int col, int emptyIndex) {
		int index = emptyIndex + col;
		if (index >= chars.length) {
			return false;
		}
		if (chars[index] == BLOCK) {
			return false;
		}
		return true;
	}

	public static boolean canRight(char[] chars, int row, int col, int emptyIndex) {
		if ((emptyIndex + 1) % col == 0) {
			return false;
		}
		if (chars[emptyIndex + 1] == BLOCK) {
			return false;
		}

		return true;
	}

	public static boolean canLeft(char[] chars, int row, int col, int emptyIndex) {
		if ((emptyIndex + 1) % col == 1) {
			return false;
		}
		if (chars[emptyIndex - 1] == BLOCK) {
			return false;
		}

		return true;
	}

	public static char[] moveUp(char[] chars, int row, int col, int emptyIndex) {
		int mvTo = emptyIndex - col;
	
		return moveTo(mvTo, chars, row, col, emptyIndex);
	}
	
	public static char[] moveDown(char[] chars, int row, int col, int emptyIndex) {
		int mvTo = emptyIndex + col;
	
		return moveTo(mvTo, chars, row, col, emptyIndex);
	}
	
	public static char[] moveRight(char[] chars, int row, int col, int emptyIndex) {
		int mvTo = emptyIndex + 1;
	
		return moveTo(mvTo, chars, row, col, emptyIndex);
	}

	public static char[] moveLeft(char[] chars, int row, int col, int emptyIndex) {
		int mvTo = emptyIndex - 1;
	
		return moveTo(mvTo, chars, row, col, emptyIndex);
	}
	
	public static int getEmptyIndex(char[] chars) {
		int emptyIndex = -1;
		for(int i = 0; i< chars.length; i++){
			if(chars[i] == EMPTY){
				emptyIndex = i;
				break;
			}
		}
		return emptyIndex;
	}
	
	private static char[] moveTo(int mvTo, char[] chars, int row, int col, int emptyIndex) {
		
		char[] charArray = chars;
		char c = charArray[mvTo];
		charArray[emptyIndex] = c;
		charArray[mvTo] = EMPTY;

		return charArray;
	}

	public static char[] restore(char[] chars, int row, int col, int oldEmptyIndex) {
		int curentEmptyIndex = -1;
		for(int i = 0; i< chars.length; i++){
			if(chars[i] == EMPTY){
				curentEmptyIndex = i;
				break;
			}
		}
		
		char c = chars[oldEmptyIndex] ;
		chars[curentEmptyIndex] = c;
		chars[oldEmptyIndex] = EMPTY;
		
		return chars;
	}
}
